<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" class="search-form">
                <el-row :gutter="20">
                    <el-col :span="3">
                        <el-form-item label="监测站点">
                            <el-select v-model="searchForm.siteId" placeholder="请选择站点" clearable
                                @change="handleSiteChange" style="width: 100%">
                                <el-option v-for="item in siteOptions" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="3">
                        <el-form-item label="监测量">
                            <el-select v-model="searchForm.metricCode" placeholder="请选择监测量" clearable
                                style="width: 100%">
                                <el-option v-for="item in monitoringOptions" :key="item.monitorCode"
                                    :label="item.monitorName" :value="item.monitorCode">
                                    <div class="monitor-option">
                                        <span class="monitor-name">{{ item.monitorName }}</span>
                                        <span class="monitor-code">{{ item.monitorCode }}</span>    
                                    </div>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="3">
                        <el-form-item label="数据状态">
                            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%">
                                <el-option label="全部" :value="null" />
                                <el-option label="正常" :value="1" />
                                <el-option label="异常" :value="0" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item label="时间范围">
                            <el-date-picker v-model="searchForm.timeRange" type="datetimerange" range-separator="至"
                                start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"
                                style="width: 100%" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <div class="form-actions">
                            <el-button type="primary" @click="handleSearch" :loading="loading">
                                <el-icon class="el-icon--left">
                                    <Search />
                                </el-icon>
                                查询
                            </el-button>
                            <el-button @click="resetSearch">
                                <el-icon class="el-icon--left">
                                    <Refresh />
                                </el-icon>
                                重置
                            </el-button>
                            <el-button type="success" @click="handleExport">
                                <el-icon class="el-icon--left">
                                    <Download />
                                </el-icon>
                                导出Excel
                            </el-button>
                        </div>
                    </el-col>
                </el-row>

            </el-form>
        </el-card>

        <!-- 数据表格区域 -->
        <el-card class="table-card">
            <el-table :data="tableData" v-loading="loading" border  style="width: 100%">
                <!-- 固定表头定义 -->
                <el-table-column prop="metricName" label="监测量名称" align="center" min-width="120" show-overflow-tooltip>
                </el-table-column>

                <el-table-column prop="metricCode" label="监测量编码" align="center" min-width="120" show-overflow-tooltip>
                </el-table-column>

                <el-table-column prop="unit" label="单位" align="center" min-width="80" show-overflow-tooltip>
                </el-table-column>

                <el-table-column prop="collectTime" label="采集时间" align="center" min-width="80">
                </el-table-column>

                <el-table-column prop="value" label="监测值" align="center" min-width="80">
                </el-table-column>

                <el-table-column prop="stationName" label="站点名称" align="center" min-width="120" show-overflow-tooltip>
                </el-table-column>

                <el-table-column prop="stationType" label="站点类型/监测点类型" align="center" min-width="120" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="reason" label="异常原因" align="center" min-width="120" show-overflow-tooltip>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container" v-if="tableData.length > 0">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :total="pagination.total" :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()

// API引入
import {
    getSiteList,
    getMonitoringListBySite,
    getTableMonitorList
} from '@/api/dispatch/detection/table'

// 搜索表单
const searchForm = reactive({
    siteId: '',
    metricCode: '',
    status: null,
    timeRange: [
        dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
        dayjs().format('YYYY-MM-DD HH:mm:ss')
    ]
})

// 分页参数
const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0
})

// 下拉选项
const siteOptions = ref([])
const monitoringOptions = ref([])

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 初始化数据
onMounted(() => {
    initData()
})

// 初始化数据
const initData = async () => {
    try {
        await fetchSiteList()

        // 设置默认站点
        if (siteOptions.value.length > 0) {
            searchForm.siteId = siteOptions.value[0].id
            await fetchMonitoringList()
        }

        // 查询数据
        await fetchTableData()
    } catch (error) {
        console.error('初始化数据失败:', error)
        ElMessage.error('初始化数据失败')
    }
}

// 获取站点列表
const fetchSiteList = async () => {
    try {
        const res = await getSiteList()
        siteOptions.value = res.data || []
    } catch (error) {
        console.error('获取站点列表失败:', error)
        ElMessage.error('获取站点列表失败')
    }
}

// 获取监测量列表
const fetchMonitoringList = async () => {
    try {
        if (!searchForm.siteId) {
            monitoringOptions.value = []
            return
        }

        const res = await getMonitoringListBySite({
            siteId: searchForm.siteId
        })
        monitoringOptions.value = res.data || []
    } catch (error) {
        console.error('获取监测量列表失败:', error)
        ElMessage.error('获取监测量列表失败')
    }
}

// 获取表格数据
const fetchTableData = async () => {
    try {
        loading.value = true

        if (!searchForm.siteId) {
            ElMessage.warning('请选择监测站点')
            return
        }

        const params = {
            siteId: searchForm.siteId,
            metricCode: searchForm.metricCode || '',
            status: searchForm.status,
            beginTime: searchForm.timeRange?.[0] || '',
            endTime: searchForm.timeRange?.[1] || '',
            pageNum: pagination.currentPage,
            pageSize: pagination.pageSize
        }

        const res = await getTableMonitorList(params)

        // 处理返回数据
        tableData.value = res.data.records
        pagination.total = res.data.total || 0
    } catch (error) {
        console.error('查询表格数据失败:', error)
        ElMessage.error('查询表格数据失败')
    } finally {
        loading.value = false
    }
}

// 处理站点变化
const handleSiteChange = (siteId) => {
    if (siteId) {
        fetchMonitoringList()
        pagination.currentPage = 1
        fetchTableData()
    } else {
        monitoringOptions.value = []
        tableData.value = []
    }
}

// 处理查询
const handleSearch = () => {
    pagination.currentPage = 1
    fetchTableData()
}

// 重置搜索
const resetSearch = () => {
    Object.assign(searchForm, {
        siteId: siteOptions.value.length > 0 ? siteOptions.value[0].id : '',
        metricCode: '',
        status: null,
        timeRange: [
            dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
            dayjs().format('YYYY-MM-DD HH:mm:ss')
        ]
    })

    pagination.currentPage = 1
    pagination.pageSize = 20

    handleSearch()
}

// 导出Excel
const handleExport = async () => {
    try {
        const params = {
            siteId: searchForm.siteId,
            metricCode: searchForm.metricCode || '',
            status: searchForm.status,
            beginTime: searchForm.timeRange?.[0] || '',
            endTime: searchForm.timeRange?.[1] || '',
            pageNum: 1,
            pageSize: 10000 // 导出所有数据
        }

        const fileName = `表格监控数据_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`

        // 使用proxy.download进行导出
        proxy.download('/dispatch/system/dispatchTableMonitor/system/monitor/table/export', params, fileName)
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 刷新数据
const refreshData = () => {
    fetchTableData()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    fetchTableData()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
    pagination.currentPage = page
    fetchTableData()
}

// 工具函数
const formatValue = (value) => {
    if (value == null || value === '') return '-'
    if (typeof value === 'number') {
        if (Number.isInteger(value)) {
            return value.toString()
        }
        return value.toFixed(2)
    }
    return value
}

const formatTime = (timeString) => {
    if (!timeString) return '-'
    try {
        return dayjs(timeString).format('YYYY-MM-DD HH:mm:ss')
    } catch {
        return timeString
    }
}

const getValueClass = (row) => {
    const value = row.currentValue
    if (value == null) return ''

    const numValue = Number(value)
    if (isNaN(numValue)) return ''

    // 获取当前监测量的阈值信息
    const monitor = monitoringOptions.value.find(item =>
        item.monitorCode === row.monitorCode
    )

    if (monitor) {
        const { alarmMin, alarmMax } = monitor
        if (alarmMin != null && numValue < alarmMin) return 'value-low'
        if (alarmMax != null && numValue > alarmMax) return 'value-high'
    }

    return 'value-normal'
}

const getStatusType = (status) => {
    switch (status) {
        case 1: return 'success'
        case 0: return 'danger'
        default: return 'info'
    }
}

const getStatusText = (status) => {
    switch (status) {
        case 1: return '正常'
        case 0: return '异常'
        default: return status || '-'
    }
}

// 计算属性
const currentSiteInfo = computed(() => {
    return siteOptions.value.find(item => item.id === searchForm.siteId) || {}
})

const currentMonitorInfo = computed(() => {
    return monitoringOptions.value.find(item => item.monitorCode === searchForm.metricCode) || {}
})
</script>

<style scoped lang="scss">
.app-container {
    padding: 20px;
}


.form-actions {
    text-align: center;
}

.table-card {
    margin-bottom: 20px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.table-info {
    display: flex;
    align-items: center;
    gap: 15px;
}

.data-count {
    color: #666;
    font-size: 14px;
}

.empty-table {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.monitor-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.monitor-name {
    font-weight: bold;
}

.monitor-code {
    color: #909399;
    font-size: 12px;
}

/* 数值样式 */
.value-normal {
    color: #67c23a;
    font-weight: bold;
}

.value-high {
    color: #f56c6c;
    font-weight: bold;
}

.value-low {
    color: #e6a23c;
    font-weight: bold;
}

:deep(.el-table) {
    .cell {
        white-space: nowrap;
        text-align: center;
    }

    th {
        text-align: center;
    }
}

:deep(.el-card) {
    margin-bottom: 20px;
}

:deep(.el-card):last-child {
    margin-bottom: 0;
}

@media (max-width: 768px) {
    .search-form .el-col {
        margin-bottom: 15px;
    }

    .table-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .table-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 5px;
    }
}
</style>